package com.qingzhu.controller.shopserver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.pojo.ShopCart;
import com.qingzhu.pojovo.ResultVo;
import com.qingzhu.service.ShopOptionService;
import com.qingzhu.service.impl.ShopOptionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Enumeration;

@WebServlet("/cart/find")
public class FindCartController extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    ShopOptionService shopOptionService = new ShopOptionServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("购物车查找服务..");

        // 获取token信息（最新方案）
        String token = req.getHeader("token");
        token = URLDecoder.decode(token,"UTF-8");
        token = token.substring(1,token.length()-1);

        // 获取cookie信息（弃用方案）
        Cookie[] cookies = req.getCookies();

        // 如果前台没有验证信息传递过来的购物车已经被清空，就直接响应1002
        if (cookies == null || cookies[0].getValue() == "") {
            if (token.equals("null") == true) {
                resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(1002,"未检测到购物车")));
            }else {
                System.out.println("检测到浏览器对cookie的支持可能不稳定...将自动切换到token技术");
                // 将购物车反序列化
                ShopCart shopCart = objectMapper.readValue(token, ShopCart.class);
                // 更新并效验购物车选项
                shopCart = shopOptionService.updateShopSption(shopCart);
                resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,shopCart)));
            }
        } else {
            String cartJson = cookies[0].getValue();
            // 解析购物车信息
            String decode = URLDecoder.decode(cartJson, "UTF-8");
            System.out.println("解码购物车："+decode);
            // 将购物车反序列化
            ShopCart shopCart = objectMapper.readValue(decode, ShopCart.class);
            // 更新并效验购物车选项
            shopCart = shopOptionService.updateShopSption(shopCart);
            resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,shopCart)));
        }
    }
}
